//
//  HZProductTextImageDetailViewController.m
//  app
//
//  Created by 刘华舟 on 15/6/3.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HZProductTextImageDetailViewController.h"
#import "HZNormalWebViewController.h"
#import "MJPhotoBrowser.h"
//model
#import "HZRemoteResult.h"
#import "HZProductCommentsVCData.h"

//model
#import "HZProductTextImageDetailModel.h"
//view
#import "HZTableView.h"
#import "HZProductTextImageDetailCell.h"
#import "MyToast.h"
#import "HZOrderGoodsEmptyView.h"
#import "HZProductTextImageDetailHeadView.h"
#import "HZProductTextImageDetailFootView.h"
#import "HZGoodsdetailToolPanel.h"
#import "MJRefreshHeaderView.h"
#import "HZgoodsParametersCell.h"

#import "HZGoodsCommentCell.h"
#import "MyToast.h"
#import "HZOrderGoodsEmptyView.h"


//tools
#import "HZMallHttpManager.h"
#import "NSDictionary+SafetyGet.h"
#import "UIImageView+URL.h"

static const NSInteger kMallHomeLabelHeight = 60;
static const NSInteger kTagButtonHeight = 80;

@interface HZProductTextImageDetailViewController()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>

@property (strong, nonatomic) UIButton *backBtn;

@property (strong, nonatomic) HZTableView *tableView;
@property (strong, nonatomic) HZOrderGoodsEmptyView *emptyView;

@property (strong, nonatomic) HZProductCommentsVCData *data;
@property (strong, nonatomic) HZRemoteResult *remoteData;

@property (strong, nonatomic) HZProductTextImageDetailHeadView *headerView;
@property (strong, nonatomic) HZProductTextImageDetailFootView *footerView;
@property (strong, nonatomic) UIView *noneHeaderView;
@property (strong, nonatomic) UIView *noneFooterView;
@property (strong, nonatomic) UIRefreshFooterController *refresshVC;
@property (strong, nonatomic) UIRefreshNotingRefreshView *notingRefreshView;

@property (assign, nonatomic, getter=isFirstShow) BOOL firstShow;

@property (strong, nonatomic) UIView *barView;
@property (strong, nonatomic) NSMutableArray *barsArray;
@property (strong, nonatomic) UIButton *lastBarBtn;

@property (strong, nonatomic) UILabel *releaseBackLabel;

@end


@implementation HZProductTextImageDetailViewController

- (NSString *)deliveryURL{
    if (_deliveryURL == nil) {
        _deliveryURL = @"";
    }
    return _deliveryURL;
}

- (NSArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [NSArray array];
    }
    return _dataArray;
}
- (void)viewDidLoad{
    [super viewDidLoad];
    
    self.view.backgroundColor = HZ_WHITE_COLOR;
    self.firstShow = YES;
    self.title = @"商品详情";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.hidden = NO;
    
    //backBtn
    self.backBtn = [[UIButton alloc] initWithFrame:CGRectOf([self.ubo fx:UB_LEFT fy:UB_TOP],
                                                            [self.ubo uw:kMallHomeLabelHeight uh:kMallHomeLabelHeight])];
    [self.backBtn setImage:[UIImage imageNamed:kImageMallArrowBackReturnRed] forState:UIControlStateNormal];
    self.backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [self.backBtn addTarget:self action:@selector(backBtnOnClickNoAnimition) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.backBtn];
    
    
    self.headerView = [[HZProductTextImageDetailHeadView alloc] initWithFrame:CGRectZero];
    self.footerView = [[HZProductTextImageDetailFootView alloc] initWithFrame:CGRectZero];
    self.footerView.targetCallerSeeDeliveryInfo = [UBTargetCaller of:self action:@selector(seeMoreDeliveryInfo)];
    
    
    self.noneHeaderView = [[UIView alloc] init];
    self.noneFooterView = [[UIView alloc] init];
    
    //添加tableView
    self.tableView = [[HZTableView alloc] initWithFrame:CGRectOf(CGPointMake(0, self.navigationAndStatusBarHeight+[self.view.ubo uy:kTagButtonHeight]),
                                                                 [self.view.ubo fw:UB_WIDTH fh:UB_HEIGHT uh:-kTagButtonHeight oh:-self.navigationAndStatusBarHeight]) style:UITableViewStylePlain];
    self.tableView.backgroundColor = HZ_CLEAR_COLOR;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = self.noneFooterView;
    self.tableView.tableHeaderView = self.noneHeaderView;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, [self.view.ubo uh:kGoodsDetailToolPanelMainViewHeight], 0);
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, [self.view.ubo uh:kGoodsDetailToolPanelMainViewHeight], 0);
    
    [self.view addSubview:self.tableView];
    
    
    self.barsArray = [NSMutableArray array];
    
    self.barView = [[UIView alloc] initWithFrame:CGRectOf([self.view.ubo fx:UB_LEFT oy:self.navigationAndStatusBarHeight],
                                                        [self.view.ubo fw:UB_WIDTH uh:kTagButtonHeight])];
    
    UIImage *noneLineImage = [[UIImage imageNamed:kImageButtonBottomLineNone] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 1, 0, 1) resizingMode:UIImageResizingModeStretch];
    UIImage *orangeLineImage = [[UIImage imageNamed:kImageButtonBottomLineOrange] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 1, 0, 1) resizingMode:UIImageResizingModeStretch];
    
    UIButton *imgTextBtn = [[UIButton alloc] initWithFrame:CGRectOf([self.barView.ubo fx:UB_LEFT fy:UB_TOP],
                                                                    [self.barView.ubo fw:UB_1_3 fh:UB_HEIGHT])];
    [imgTextBtn setTitle:@"图文详情" forState:UIControlStateNormal];
    [imgTextBtn setTitle:@"图文详情" forState:UIControlStateSelected];
    [imgTextBtn setTitleColor:HZ_MALL_TEXT_BLACK_COLOR forState:UIControlStateNormal];
    [imgTextBtn setTitleColor:HZ_MALL_MAIN_THEME_ORANGE forState:UIControlStateSelected];
    [imgTextBtn setBackgroundImage:noneLineImage forState:UIControlStateNormal];
    [imgTextBtn setBackgroundImage:orangeLineImage forState:UIControlStateSelected];
    imgTextBtn.tag = kGoodsMoreDetailBarTagImageText;
    [imgTextBtn addTarget:self action:@selector(barBtnOnClick:) forControlEvents:UIControlEventTouchUpInside];
    imgTextBtn.titleLabel.font = JKAppGlobleFontMenu;
    imgTextBtn.selected = NO;
    [self.barView addSubview:imgTextBtn];
    [self.barsArray addObject:imgTextBtn];
    
    UIButton *argBtn = [[UIButton alloc] initWithFrame:CGRectOf([self.barView.ubo fx:UB_1_3 fy:UB_TOP],
                                                                    [self.barView.ubo fw:UB_1_3 fh:UB_HEIGHT])];
    [argBtn setTitle:@"产品参数" forState:UIControlStateNormal];
    [argBtn setTitle:@"产品参数" forState:UIControlStateSelected];
    [argBtn setTitleColor:HZ_MALL_TEXT_BLACK_COLOR forState:UIControlStateNormal];
    [argBtn setTitleColor:HZ_MALL_MAIN_THEME_ORANGE forState:UIControlStateSelected];
    [argBtn setBackgroundImage:noneLineImage forState:UIControlStateNormal];
    [argBtn setBackgroundImage:orangeLineImage forState:UIControlStateSelected];
    argBtn.tag = kGoodsMoreDetailBarTagArgument;
    [argBtn addTarget:self action:@selector(barBtnOnClick:) forControlEvents:UIControlEventTouchUpInside];
    argBtn.titleLabel.font = JKAppGlobleFontMenu;
    argBtn.selected = NO;
    [self.barView addSubview:argBtn];
    [self.barsArray addObject:argBtn];
    
    UIButton *commentBtn = [[UIButton alloc] initWithFrame:CGRectOf([self.barView.ubo fx:UB_2_3 fy:UB_TOP],
                                                                    [self.barView.ubo fw:UB_1_3 fh:UB_HEIGHT])];
    [commentBtn setTitle:@"口碑评价" forState:UIControlStateNormal];
    [commentBtn setTitle:@"口碑评价" forState:UIControlStateSelected];
    [commentBtn setTitleColor:HZ_MALL_TEXT_BLACK_COLOR forState:UIControlStateNormal];
    [commentBtn setTitleColor:HZ_MALL_MAIN_THEME_ORANGE forState:UIControlStateSelected];
    [commentBtn setBackgroundImage:noneLineImage forState:UIControlStateNormal];
    [commentBtn setBackgroundImage:orangeLineImage forState:UIControlStateSelected];
    commentBtn.tag = kGoodsMoreDetailBarTagComment;
    [commentBtn addTarget:self action:@selector(barBtnOnClick:) forControlEvents:UIControlEventTouchUpInside];
    commentBtn.titleLabel.font = JKAppGlobleFontMenu;
    commentBtn.selected = NO;
    [self.barView addSubview:commentBtn];
    [self.barsArray addObject:commentBtn];

    [self.view addSubview:self.barView];
    

    
    self.releaseBackLabel = [[UILabel alloc] initWithFrame:CGRectOf([self.barView.ufo fx:UB_LEFT fy:UB_BOTTOM],
                                                                    [self.barView.ubo fw:UB_WIDTH uh:kTagButtonHeight])];
    
    self.releaseBackLabel.text = @"";
    self.releaseBackLabel.textAlignment = NSTextAlignmentCenter;
    self.releaseBackLabel.textColor = HZ_MALL_TEXT_M_LIGHTGRAY_COLOR;
    self.releaseBackLabel.font = JKAppGlobleFontContentText;
    
    //[self.tableView addSubview:self.releaseBackLabel];
    
    [self.view insertSubview:self.releaseBackLabel belowSubview:self.tableView];
    //[self.view addSubview:self.releaseBackLabel];
    
    //    //MJHeader view
    //
    //    MJRefreshHeaderView *mjHeaderView = [MJRefreshHeaderView header];
    //    mjHeaderView.pullToRefreshText = @"下拉回到“商品详情”";
    //    mjHeaderView.refreshingText = @"";
    //    mjHeaderView.activityView.hidden = YES;
    //    [mjHeaderView.activityView removeFromSuperview];
    //    mjHeaderView.releaseToRefreshText = @"释放回到”商品详情“";
    //    mjHeaderView.customArrowImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:kImageArrowBottom]];
    //    mjHeaderView.beginRefreshingCallback = ^{
    //        [self performSelector:@selector(backBtnOnClickNoAnimition) withObject:nil afterDelay:0.5];
    //        //[self.navigationController popViewControllerAnimated:YES];
    //    };
    //    [self.tableView addSubview:mjHeaderView];
    
    self.refresshVC = [[UIRefreshFooterController alloc] initWithTableView:self.tableView caller:[UBTargetCaller of:self action:@selector(loadMoreData)]];
    self.notingRefreshView = [[UIRefreshNotingRefreshView alloc] initWithView:self.tableView viewController:self tryAgain:@selector(loadProductCommentsData)];
    
    self.tableView.footerRefreshController = self.refresshVC;
    self.tableView.nothingRefreshView = self.notingRefreshView;
    
    self.emptyView = [[HZOrderGoodsEmptyView alloc] initWithFrame:CGRectOf([self.ubo fx:UB_LEFT fy:UB_TOP], [self.ubo fw:UB_WIDTH fh:UB_HEIGHT])];
    [self.emptyView hide];
    [self.view addSubview:self.emptyView];

    
    self.defaultBarTag = kGoodsMoreDetailBarTagImageText;
    
    self.remoteData = [HZRemoteResult target:self action:@selector(finishedLoadGoodsSearchData:)];
    
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

- (void)showMoreDetailsWithDefaultTag:(NSInteger)tag{
    [self.view addSubview:self.toolPanel];
    
    [self barBtnOnClick:[self.barsArray objectAtIndex:tag-2000]];
}

- (void)barBtnOnClick:(UIButton *)barBtn{
    self.lastBarBtn.selected = NO;
    self.lastBarBtn = barBtn;
    self.lastBarBtn.selected = YES;
    
    self.defaultBarTag = self.lastBarBtn.tag;
    
    if (self.defaultBarTag == kGoodsMoreDetailBarTagImageText) {
        
        [self.emptyView hide];
        
        self.dataArray = self.deliveryDataArray;
        
        
        
        [self.tableView reloadData];
        
    }else if(self.defaultBarTag == kGoodsMoreDetailBarTagArgument){
        
        [self.emptyView hide];
        
        self.dataArray = self.arvsDataArray;
        
        
        
        [self.tableView reloadData];
        
    }else if (self.defaultBarTag == kGoodsMoreDetailBarTagComment){
        
        
        
        self.dataArray = [NSMutableArray array];
        
        [self.tableView reloadData];
        
        if (([self.productID length]) && (self.data == nil)) {
            [self.tableView.nothingRefreshView showLoadingMsg:nil errorMsg:@"加载失败，点击重试"];
            [self loadProductCommentsData];
        }else{
            
            self.dataArray = self.data.commentsArray;
            
            
            if (self.data.commentsArray.count == 0) {
                [self.emptyView showWithMessage:@"该商品暂无评论！"];
            }
            
            [self.tableView reloadData];
        }
    }
    
}

#pragma mark 加载数据
- (void)loadProductCommentsData{
    HZMallHttpManager *httpManager = [HZMallHttpManager shareHttpRequestMananger];
    NSDictionary *params = @{APIKEY_mall_product_id:self.productID};
    [httpManager loadProductCommentsListWithParams:params result:self.remoteData];
}
#pragma mark 点击返回
- (void)backBtnOnClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)backBtnOnClickNoAnimition{
    [self.navigationController popViewControllerAnimated:NO];
}

#pragma mark 加载更多数据
- (void)loadMoreData{
    
    if (self.defaultBarTag == kGoodsMoreDetailBarTagComment) {
        if (self.data.noMoreData) {
            [self.tableView endRefreshingAll];
            [MyToast showDefaultBottonWithText:@"已显示全部评论"];
        }else{
            HZGoodsCommentModel *model = [self.data.commentsArray lastObject];
            NSString *lastID = @"";
            if (model) {
                lastID = model.userID;
            }
            NSDictionary *params = @{APIKEY_mall_product_id:self.productID,
                                     APIKEY_mall_lastid:lastID};
            HZMallHttpManager *httpManager = [HZMallHttpManager shareHttpRequestMananger];
            [httpManager loadMoreProductCommentsListWithParams:params result:self.remoteData];
        }
    }else{
        [MyToast showDefaultBottonWithText:@"已显示全部内容"];
        [self.tableView endRefreshingAll];
    }
 
}

#pragma mark 完成加载数据
- (void)finishedLoadGoodsSearchData:(HZRemoteResult *)result{
    [self.tableView endRefreshingAll];
    
    if (result.response.status == JKResponseServerError || result.response.status == JKResponseLocalError) {
        [self.tableView.nothingRefreshView activeStop];
        [self.emptyView hide];
    }else if (result.response.status == JKResponseOK) {
        [self.tableView.nothingRefreshView remove];
        
        self.data = result.info;
        
        [self.emptyView hide];
        
        if (self.data) {
            
            self.dataArray = self.data.commentsArray;
            
            self.tableView.footerRefreshController = self.refresshVC;
            self.tableView.nothingRefreshView = self.notingRefreshView;
            
            self.tableView.tableFooterView = self.noneFooterView;
            self.tableView.tableHeaderView = self.noneHeaderView;
            
            [self.tableView reloadData];
            
        }else{
            [self.tableView.nothingRefreshView remove];
            if(result.response.status == JKResponseTail){
                [self.emptyView showWithMessage:@"该商品暂无评论!"];
            }else{
                [self.emptyView showWithMessage:result.response.message];
            }
        }
        [self.tableView reloadData];
    }else{
        self.data = result.info;
        [self.tableView.nothingRefreshView remove];
        if(result.response.status == JKResponseTail){
            [self.emptyView showWithMessage:@"该商品暂无评论!"];
        }else{
            [self.emptyView showWithMessage:result.response.message];
        }
        
    }
}

#pragma mark 点击查看大图
- (void)seeCommentsPics:(NSDictionary *)dict{
    MJPhotoBrowser *photoBrowser = [[MJPhotoBrowser alloc] init];
    NSMutableArray *photoArray = [NSMutableArray array];
    NSArray *pics = [dict arrayForKey:@"array"];
    NSString *picURL = [dict stringForKey:@"urlKey" nilValue:@""];
    NSInteger index = [dict integerForKey:@"index"];
    for (NSDictionary *pic in pics) {
        MJPhoto *photo = [[MJPhoto alloc] init];
        //展位图
        UIImageView *photoPlaceHolder = [[UIImageView alloc] init];
        [photoPlaceHolder setImageWithURL:[pic stringForKey:picURL nilValue:@""]];
        photo.srcImageView = photoPlaceHolder;
        //原图
        photo.url = [NSURL URLWithString:[[pic stringForKey:picURL nilValue:@""] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        photo.save = NO;
        [photoArray addObject:photo];
    }
    photoBrowser.photos = [NSArray arrayWithArray:photoArray];
    
    if (index>=pics.count) {
        index = 0;
    }
    photoBrowser.currentPhotoIndex = index;
    [photoBrowser show];
}

#pragma mark 查看更多物流配送信息
- (void)seeMoreDeliveryInfo{
    HZNormalWebViewController *salesVC = [[HZNormalWebViewController alloc] init];
    salesVC.webTitle = @"配送说明";
    salesVC.webURL = self.deliveryURL;
    [self.navigationController pushViewController:salesVC animated:YES];
}

#pragma mark UITableViewDelegate UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.defaultBarTag == kGoodsMoreDetailBarTagImageText) {
        
        HZProductTextImageDetailCell *cell = [HZProductTextImageDetailCell cellWithTableView:(HZTableView *)tableView];
        cell.model = [self.dataArray objectAtIndex:indexPath.row];
        return cell;
        
    }else if(self.defaultBarTag == kGoodsMoreDetailBarTagArgument){
        
        HZGoodsParametersCell *cell = [HZGoodsParametersCell cellWithTableView:(HZTableView *)tableView];
        [cell showWithDictionry:[self.arvsDataArray objectAtIndex:indexPath.row] nameKey:APIKEY_mall_name valueKey:APIKEY_mall_val];
        return cell;
        
    }else if (self.defaultBarTag == kGoodsMoreDetailBarTagComment){
        
        HZGoodsCommentCell *cell = [HZGoodsCommentCell cellWithTableView:(HZTableView *)tableView];
        cell.picsTargetCaller = [UBTargetCaller of:self action:@selector(seeCommentsPics:)];
        cell.model = [self.data fetchCellModelAtRow:indexPath.row];
        return cell;
    }
    
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.defaultBarTag == kGoodsMoreDetailBarTagImageText) {
        
        HZProductTextImageDetailModel *model = [self.dataArray objectAtIndex:indexPath.row];
        return model.cellHeight;
        
    }else if(self.defaultBarTag == kGoodsMoreDetailBarTagArgument){
        return kHZGoodsParametersCellHeight;
        
    }else if (self.defaultBarTag == kGoodsMoreDetailBarTagComment){
        
        HZGoodsCommentModel *model = [self.data fetchCellModelAtRow:indexPath.row];
        return model.cellHeight;
    }
    return 44.0f;
}

- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
 
}

#pragma mark UIScrollViewDelegate
//完成拖动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if(scrollView.contentOffset.y <= -(44)){
        self.releaseBackLabel.text = @"释放回到商品详情";
    }else if(scrollView.contentOffset.y > -(44) && scrollView.contentOffset.y <= 0){
        self.releaseBackLabel.text = @"下拉回到商品详情";
    }else{
        self.releaseBackLabel.text = @"";
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    if(scrollView.contentOffset.y < -(44)){
        [self performSelector:@selector(backBtnOnClickNoAnimition) withObject:nil afterDelay:0.5];
    }
}



@end
